from openai import OpenAI
import streamlit as st
import re

st.title("unicode tool")

model_name = st.sidebar.selectbox(
    "模型",
    ("qwen3-32b", "qwen-plus-latest"),
    index=0,
    key="model_name",
)


client = OpenAI(
    api_key=st.secrets["DASHSCOPE_API_KEY"],
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    )

if "openai_model" not in st.session_state:
    st.session_state["openai_model"] = "gpt-3.5-turbo"

if "messages" not in st.session_state:
    st.session_state.messages = []

for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.markdown(message["content"])


 
def encode_non_english_chars(text):
    """
    将字符串中的非英文字符（非ASCII字母、数字、空格及常见英文标点）转换为Unicode编码
    
    参数:
        text (str): 输入字符串
        
    返回:
        str: 处理后的字符串，非英文字符被替换为\\uXXXX形式
    """
    result = []
    for char in text:
        # 检查字符是否是英文字母、数字、空格或常见英文标点
        if re.match(r'^[a-zA-Z0-9\s!\"#\$%&\'\(\)\*\+,-\./:;<=>\?@\[\\\]\^_`{\|}~]$', char):
            result.append(char)
        else:
            # 转换为Unicode转义序列
            encoded = char.encode('unicode-escape').decode('ascii')
            # 处理可能的转义字符（如\n等）
            if encoded.startswith('\\u') or encoded.startswith('\\U'):
                result.append(encoded)
            else:
                # 对于无法用\u表示的字符（如ASCII控制字符），使用\x转义
                result.append(encoded)
    return ''.join(result)

if prompt := st.chat_input("What is up?"):
    # 查询向量数据库

    # 不需要记录上下文，直接清空
    st.session_state.messages = []

    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.markdown(prompt)

    with st.chat_message("assistant"):
        response = st.write(encode_non_english_chars(prompt))
    st.session_state.messages.append({"role": "assistant", "content": response})